package com.cloud.base.proxy;

import com.cloud.base.annotation.ApiProxy;
import com.cloud.base.bean.OpenConfig;
import com.common.utils.tools.BusinessException;
import com.common.utils.tools.JsonUtils;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ApiInvocationProxy implements InvocationHandler {

    private Class<?> interfaceClass;

    public Object bind(Class<?> cls) {
        this.interfaceClass = cls;
        return Proxy.newProxyInstance(cls.getClassLoader(), new Class[] {interfaceClass}, this);
    }

    final OpenConfig config;

    ApiInvocationProxy() {
        config = null;
    }

    public ApiInvocationProxy(OpenConfig config) {
        this.config = config;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
        Class<?>[] interfaces = proxy.getClass().getInterfaces();
        ApiProxy apiProxy = null;
        for (Class<?> cls : interfaces) {
            apiProxy = cls.getAnnotation(ApiProxy.class);
            if (apiProxy != null) {
                break;
            }
        }
        if (apiProxy == null) {
            throw new BusinessException("接口没有标注此ApiProxy注解");
        }
        ApiRequest apiRequest = buildApiRequest(apiProxy, method, config);
        String json = apiRequest.request((Serializable) args[0]);
        return JsonUtils.fromJson(json, method.getReturnType());
    }

    private ApiRequest buildApiRequest(ApiProxy apiProxy, Method method, OpenConfig config) {
        return new ApiRequest(apiProxy, method, config);
    }


}
